﻿//***********************************************************************************************
//* File Name	: ImapRepository.cs
//* Description	: This class is Repository implementation for IMAP channel
//* 
//* Author		: Ashutosh Phoujdar(ashu.fouzdar@gmail.com)
//* Date		: 14-September-2014
//* ***********************************************************************************************


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ActiveUp.Net.Mail;

namespace EmailFactory
{
    public class ImapRepository : EmailFactory.IEmailRepository
    {
        private Imap4Client _client = null;
        public ImapRepository(string mailServer, int port, bool ssl, string login, string password)
        {
            if (ssl)
                Client.ConnectSsl(mailServer, port);
            else
                Client.Connect(mailServer, port);
            Client.Login(login, password);
        }

        public MessageCollection GetAllMails(string mailBox)
        {
            return GetMails(mailBox, "ALL");
        }

        public MessageCollection GetUnreadMails(string mailBox)
        {
            return GetMails(mailBox, "UNSEEN");
        }

        public Message GetMailByOrdinal(string mailBox, int messageOrdinal)
        {
            Message message = null;
            Mailbox mails = Client.SelectMailbox(mailBox);
            if (messageOrdinal < mails.MessageCount)
            {
                message = mails.Fetch.MessageObject(messageOrdinal);
            }
            return message;
        }

        protected Imap4Client Client
        {
            get
            {
                if (_client == null)
                    _client = new Imap4Client();
                return _client;
            }
        }

        private MessageCollection GetMails(string mailBox, string searchPhrase)
        {
            Mailbox mails = Client.SelectMailbox(mailBox);
            MessageCollection messages = mails.SearchParse(searchPhrase);
            return messages;
        }
    }
}
